<template>
    <div class="sider-left">
        <div class="header" v-if="userInfo">
            <div class="avatar">
                <img class="img" :src="userInfo.user_icon">
            </div>
            <div class="info">
                <h3 class="nickname">
                    <span class="name">{{userInfo.nick_name}}</span>
                    <el-dropdown trigger="click" @command="handleCommand">
                        <a class="opt"><icon type="menu" color="#9da4b3" :size="30"></icon></a>
                        <el-dropdown-menu slot="dropdown">
                            <template v-if="notificationStatus != 'denied'">
                                <el-dropdown-item  v-if="noticeStatus == 0" style="display: flex;align-items: center;color: #23242B;" command="status1"><img style="margin-right: 5px;" src="../../assets/notice_icon.png" alt="">关闭消息通知</el-dropdown-item>
                                <el-dropdown-item v-if="noticeStatus == 1" style="display: flex;align-items: center;color: #23242B;" command="status0"><img style="margin-right: 5px;" src="../../assets/notice_icon.png" alt="">开启消息通知</el-dropdown-item>
                            </template>
                            <el-dropdown-item style="display: flex;align-items: center;color: #23242B;" command="logout"><img style="margin-right: 5px;" src="../../assets/logout_icon.png" alt="">退出登录</el-dropdown-item>
                        </el-dropdown-menu>
                    </el-dropdown>
                </h3>
            </div>
        </div>
        <search-bar></search-bar>
        <div class="tab">
            <div class="tab-item" data-type="message" @click="handleTabChange($event)">
                <a style="cursor: pointer;"><icon type="message" :color="currentTab == 'message' ? '#4288ff' : '#9da4b3'" :size="30"></icon></a>
            </div>
            <div class="tab-item" data-type="friend" @click="handleTabChange($event)">
                <a style="cursor: pointer;"><icon type="person" :color="currentTab == 'friend' ? '#4288ff' : '#9da4b3'" :size="30"></icon></a>
            </div>
            <div class="tab-item" data-type="group" @click="handleTabChange($event)">
                <a style="cursor: pointer;"><icon type="group" :color="currentTab == 'group' ? '#4288ff' : '#9da4b3'" :size="30"></icon></a>
            </div>
        </div>
        <div class="group-tab" v-if="currentTab == 'group'">
            <div class="tab-item" :class="{'active': currentGroupTab == 'myself'}" data-type="myself" @click="handleGroupTabChange($event)">
                <a>我创建的群</a>
            </div>
            <div class="tab-item" :class="{'active': currentGroupTab == 'join'}" data-type="join" @click="handleGroupTabChange($event)">
                <a>我加入的群</a>
            </div>
        </div>
        <div class="nav-view" :style="{top: currentTab == 'group' ? '200px' : '160px'}">
            <div class="nav-message" :class="{'active': !online}">
                <img class="connect" src="../../assets/loading.gif" alt="" v-if="reConnectStatus">
                <icon type="warning" color="#f66260" :size="18" v-else></icon>
                <span class="text">{{reConnectStatus ? '连接中...' : '网络连接不可用'}}</span>
                <div class="button" @click="reConnect" v-if="!reConnectStatus">点击重连</div>
            </div>
            <el-scrollbar ref="listBar" style="height: 100%;" :native="false" :noresize="true">
                <p class="nav-loading" v-if="loading">
                    <img src="../../assets/loading.gif" alt="">
                    <span>正在获取数据...</span>
                </p>
                <p class="nav-loading" v-show="currentTab == 'message' && (!chatList || chatList.length == 0)">
                    <span>暂时没有新的会话</span>
                </p>
                <div class="chat-list" v-show="currentTab == 'message' && chatList && updatedImg">
                    <div class="chat-item" :class="{'active': item.id == currentChatId}" :id="item.id+'_id'" v-for="(item, index) in chatList" :key="index" @contextmenu.prevent="right($event, item.id)" @click="handleChat(item)">

                        <div class="ext">
                            <p class="attr">{{item.msgData.length != 0 ? getDateFormat(item.msgData[item.msgData.length - 1].date, 'hh:mm') : ''}}</p>
                        </div>
                        <div class="avatar">
                            <img class="img" :src="item.icon" alt="" v-if="item.icon != '' && item.msgType == 11">
                            <img class="img" src="../../assets/person_icon.jpg" v-if="item.icon == '' && item.msgType == 11">
                            <template v-if="item.msgType == 13">
                                <group-avatar v-lazy-container="{ selector: 'img' }" :id="item.id"></group-avatar>
                            </template>
                            <!--<img class="img" src="../../assets/group_icon.png" v-if="item.icon == '' && item.msgType == 13">-->
                        </div>
                        <div class="info">
                            <h3 class="nickname">
                                <span v-if="item.id != '1529065300000'" class="text">{{item.name}}</span>
                                <span v-if="item.id == '1529065300000'" class="text" style="color: #80AFFF;">{{item.name}}</span>
                                <!--<span class="text">草稿</span>-->
                            </h3>
                            <p class="msg" v-if="$store.state.chat.chatInputObj[item.id].content && $store.state.chat.currentChatId != item.id"><span style="color: #ffb53b;margin-right: 3px;">[草稿]</span>{{$store.state.chat.chatInputObj[item.id].content}}</p>
                            <p class="msg" v-else-if="allowContentType(item) == 0" v-html="item.msgData.length != 0 ? getEmojiImg(JSON.parse(item.msgData[item.msgData.length - 1].msg).content) : ''"></p>
                            <p class="msg" v-else-if="allowContentType(item) == 7" v-html="item.msgData.length != 0 ? getEmojiImg(JSON.parse(item.msgData[item.msgData.length - 1].msg).rc) : ''"></p>
                            <p class="msg" v-else-if="allowContentType(item) == 1">
                                <template v-if="item.msgData[item.msgData.length - 1].own == 1 || (item.msgData[item.msgData.length - 1].groupid && item.msgData[item.msgData.length - 1].senderid == userInfo.id)">你撤回了一条消息</template>
                                <template v-else-if="item.msgType == 11">对方撤回了一条消息</template>
                                <template v-else>有人撤回了一条消息</template>
                            </p>
                            <p class="msg" v-else-if="allowContentType(item) == 3">
                                [图片]
                            </p>
                            <p class="msg" v-else-if="allowContentType(item) == 4">
                                [文件]
                            </p>
                            <p class="msg" v-else-if="allowContentType(item) == 6">
                                [视频]
                            </p>

                            <p class="msg" v-else-if="allowContentType(item) == 10">
                                [动态表情]
                            </p>

                            <p class="msg" v-else-if="allowContentType(item) == 8">
                                我发了一条语音，请在手机上查看
                            </p>

                            <p class="msg" v-else-if="allowContentType(item) == 9">
                                我发了一个红包，请在手机上查看
                            </p>
                            <p v-else class="msg">
                                不支持消息类型，请在手机上查看
                            </p>
                        </div>
                        <template v-if="item.mute == 1 || item.mute == 2">
                            <div v-if="item.count != 0" class="mute-num"></div>
                            <div class="mute" >
                                <img src="../../assets/icon_mute.png" title="消息免打扰" alt="">
                            </div>
                        </template>

                        <div class="num" v-if="item.count != 0 && (item.mute == 0 || item.mute == 3)">
                            {{item.count}}
                        </div>
                    </div>
                </div>
                <div class="person-list friend-list" v-show="currentTab == 'friend' && friendList">
                    <template v-for="(value, key, i) in friendList">
                        <h4 class="person-title" :key="i">{{key.toUpperCase()}}</h4>
                        <div class="person-item" :id="'firend_'+item.id" :class="{'active': item.id == currentUser.id}" v-for="item in value" :key="item.id" @click="handlePerson(item)">
                            <div class="avatar">
                                <img class="img" :src="item.usericon" alt="" v-if="item.usericon != ''">
                                <img class="img" src="../../assets/person_icon.jpg" alt="" v-else>
                            </div>
                            <div class="info">
                                <h4 class="nickname">{{item.remark != '' ? item.remark : item.nickname}}</h4>
                            </div>
                        </div>
                    </template>
                </div>
                <div v-show="currentTab == 'group' && groupList">
                    <div class="person-list group-list-myself">
                        <template v-for="(item, index) in groupList">
                            <div class="person-item" :id="'group_'+item.id" :class="{'active': item.id == currentGroup.id}" :key="index" v-show="currentGroupTab == 'myself' && userInfo.id == item.owner" @click="handleGroup(item)">
                                <div class="avatar">
                                    <group-avatar v-lazy-container="{ selector: 'img' }" :id="item.id"></group-avatar>
                                </div>
                                <div class="info">
                                    <h4 class="nickname">{{item.group_name}}</h4>
                                </div>
                            </div>
                        </template>
                    </div>
                    <div class="person-list group-list-join">
                        <template v-for="(item, index) in groupList">
                            <div class="person-item" :id="'groupjoin_'+item.id" :class="{'active': item.id == currentGroup.id}" :key="index" v-show="currentGroupTab == 'join' && userInfo.id != item.owner" @click="handleGroup(item)">
                                <div class="avatar">
                                    <group-avatar v-lazy-container="{ selector: 'img' }" :id="item.id"></group-avatar>
                                </div>
                                <div class="info">
                                    <h4 class="nickname">{{item.group_name}}</h4>
                                </div>
                            </div>
                        </template>
                    </div>
                </div>
            </el-scrollbar>
        </div>
        <el-dialog title="提示" :visible.sync="dialogLogout" width="500px" :append-to-body="true">
            <span>退出登录后将无法接收新消息，确定退出登录？</span>
            <span slot="footer" class="dialog-footer">
                <el-button @click="dialogLogout = false">取 消</el-button>
                <el-button type="primary" @click="logout">确 定</el-button>
            </span>
        </el-dialog>
        <context-menu :visible="contextMenuShow" position="left" :clickPosition="clickPosition" @close="closeContextMenu" @confirm="clickContextMenu($event)"></context-menu>
    </div>
</template>
<script>
import { baseApi } from '@/api'
import searchBar from '@/components/search-bar/index'
import contextMenu from '@/components/context-menu/index'
import groupAvatar from '@/components/group-avatar/index'
import icon from '@/components/icon/index'
import scrollIntoView from '@/utils/scroll-into-view'
import utils from '@/utils/common'
import emoji from '@/utils/emoji'

export default {
    data() {
        return {
            updatedImg: true,
            preDelId: '',
            currentTab: 'message',
            currentGroupTab: 'myself',
            clickPosition: null,
            dialogLogout: false,
            contextMenuShow: false,
            // 默认开启，0：开启，1：关闭
            noticeStatus:localStorage.getItem('noticeStatus')?localStorage.getItem('noticeStatus'):0,
            notificationStatus: window.Notification.permission
        }
    },
    computed: {
        loading() {
            return this.$store.state.base.loading
        },
        userInfo() {
            return this.$store.state.base.userInfo
        },
        chatList() {
            return this.$store.state.chat.chatList
        },
        friendList() {
            return this.$store.state.base.friendList
        },
        groupList() {
            return this.$store.state.base.groupList
        },
        currentChatId() {
            return this.$store.state.chat.currentChatId
        },
        currentUser() {
            if (this.$store.state.base.currentUser) {
                return this.$store.state.base.currentUser
            } else {
                return {}
            }
        },
        currentGroup() {
            if (this.$store.state.base.currentGroup) {
                return this.$store.state.base.currentGroup
            } else {
                return {}
            }
        },
        online() {
            return this.$store.state.base.online
        },
        reConnectStatus() {
            return this.$store.state.base.reConnect
        }
    },
    components: {
        searchBar,
        icon,
        contextMenu,
        groupAvatar
    },
    watch: {
        chatList() {
          this.updatedImg = false
          this.$nextTick(() => {
              this.updatedImg = true
          })
        },
        $route(to, from) {
            if (to.path.indexOf('message') != -1) {
                this.currentTab = 'message'
            }
        },
        currentTab(val) {
            this.$store.dispatch('updateCurrentTab', val)
        },
        currentGroupTab(val) {
            this.$store.dispatch('updateCurrentGroupTab', val)
        }
    },
    methods: {
        getDateFormat(date, format) {
            return utils.dateFormat(date, format)
        },
        _resetScorll() {
            this.$nextTick(() => {
                if (this.currentTab == 'message') {
                    let currentChatId = this.$store.state.chat.currentChatId
                    let target = document.getElementById(currentChatId + '_id')
                    let container = document.querySelector('.chat-list').parentNode.parentNode
                    scrollIntoView(container, target)
                } else if (this.currentTab == 'friend') {
                    let currentUser = this.$store.state.base.currentUser
                    let container = document.querySelector('.friend-list').parentNode.parentNode
                    if (currentUser) {
                        let target = document.getElementById('firend_' + currentUser.id)
                        scrollIntoView(container, target)
                    } else {
                        container.scrollTop = 0
                    }
                } else {
                    let currentGroup = this.$store.state.base.currentGroup
                    let isOwn = false
                    if (currentGroup) {
                        isOwn = currentGroup.owner == this.userInfo.id
                    }
                    if (this.currentGroupTab == 'myself') {
                        let container = document.querySelector('.group-list-myself').parentNode.parentNode.parentNode
                        if (currentGroup && isOwn) {
                            let target = document.getElementById('group_' + currentGroup.id)
                            scrollIntoView(container, target)
                        } else {
                            container.scrollTop = 0
                        }
                    } else {
                        let container = document.querySelector('.group-list-join').parentNode.parentNode.parentNode
                        if (currentGroup && !isOwn) {
                            let target = document.getElementById('groupjoin_' + currentGroup.id)
                            scrollIntoView(container, target)
                        } else {
                            container.scrollTop = 0
                        }
                    }
                }
            })
        },
        handleTabChange(e) {
            let currentTab = e.currentTarget.getAttribute('data-type')
            this.$router.push({ name: currentTab })
            this.currentTab = currentTab
            this._resetScorll()
        },
        handleGroupTabChange(e) {
            let currentGroupTab = e.currentTarget.getAttribute('data-type')
            this.currentGroupTab = currentGroupTab
            this._resetScorll()
        },
        handleCommand(command) {
            if (command == 'logout') {
                this.dialogLogout = true
            } else if (command == 'status1') {
                this.noticeStatus = 1
                localStorage.setItem('noticeStatus', 1)
            } else if (command == 'status0') {
                this.noticeStatus = 0
                localStorage.setItem('noticeStatus', 0)
            }
        },
        handleChat(item) {
            if (item.msgType == 13) {
                baseApi.getGroupSubs({ group_id: item.id }).then(res => {
                    if (res.code == 200) {
                        this.$store.dispatch('setCrrentGroupSubs', res.data)
                    } else {
                        // this.$socket.close()
                        this.$confirm('您的授权已失效，请重新登录！', '提示', {
                            confirmButtonText: '知道了',
                            showClose: false,
                            showCancelButton: false,
                            closeOnClickModal: false,
                            closeOnPressEscape: false,
                            type: 'warning'
                        }).then(() => {
                            sessionStorage.removeItem('key')
                            this.$store.dispatch('resetBase')
                            this.$store.dispatch('resetChat')
                            this.$router.push({ path: '/login' })
                            // window.location.href = window.location.protocol + '//' + window.location.host + '/login'
                        })
                    }
                })
            }
            this.$store.dispatch('setCurrentChat', item.id)
            if (document.title != '默往网页版') {
                if (window.newsInterval) {
                    clearInterval(window.newsInterval)
                    document.title = '默往网页版'
                }
            }
        },
        logout() {
            this.dialogLogout = false
            this.$socket.close()
            sessionStorage.removeItem('key')
            this.$store.dispatch('resetBase')
            this.$store.dispatch('resetChat')
            this.$router.push({ path: '/login' })
        },
        right(e, id) {
            this.contextMenuShow = true
            this.clickPosition = {
                clientX: e.clientX,
                clientY: e.clientY
            }
            this.preDelId = id
        },
        handlePerson(item) {
            this.$store.dispatch('setCurrentUser', item)
            if (this.$route.path.indexOf('friend') < 0) {
                this.$router.push({ path: '/friend' })
            }
        },
        handleGroup(item) {
            this.$store.dispatch('setCurrentGroup', item)
        },
        getEmojiImg(str) {
            return emoji.transToEmojiImg(str)
        },
        closeContextMenu() {
            this.contextMenuShow = false
        },
        clickContextMenu(e) {
            if (e == 'del') {
                this.$store.dispatch('delChatListItem', this.preDelId)
                this.preDelId = ''
                this.contextMenuShow = false
            }
        },
        allowContentType(item) {
            let status = 0
            let msgData = []
            if (item.msgData.length > 0) {
                msgData = item.msgData
                let type = msgData[msgData.length - 1].contentType
                let destroy = msgData[msgData.length - 1].destroy
                if (type == 1021 || type == 1007) {
                    if (destroy == 0) {
                        status = 0
                    } else {
                        status = 5
                    }
                } else if (type == 55) {
                    status = 1
                } else if (type == 1022 || type == 1018) {
                    if (destroy == 0) {
                        if (type == 1022) {
                            status = 3
                        } else {
                            status = 4
                        }
                    } else {
                        status = 5
                    }
                } else if (type == 1004) {
                    status = 6
                } else if (type == 1012) {
                    status = 7
                } else if (type == 1013) {
                    status = 8
                } else if (type == 1011 || type == 1016) {
                    status = 9
                } else if (type == 1015) {
                    status = 10
                } else {
                    status = 2
                }
            }
            return status
        },
        reConnect() {
            this.$store.dispatch('changeReconnectStatus', true)
            this.$emit('initSocket')
        }
    },
    updated() {
        this.$refs['listBar'].update()
    }
}
</script>
<style>
    .sider-left .chat-item:focus {
        outline: none !important;
    }
    .sider-left .el-scrollbar__view {
        outline: none !important;
    }
    .sider-left .chat-list {
        outline: none !important;
    }
</style>

<style lang="less" scoped>
.sider-left {
    position: relative;
    width: 280px;
    height: 100%;
    float: left;
    background: #323843;
    .header {
        padding: 18px;
        position: relative;
        .avatar {
            display: table-cell;
            vertical-align: middle;
            word-wrap: break-word;
            word-break: break-all;
            white-space: nowrap;
            padding-right: 10.625px;
            .img {
                width: 40px;
                height: 40px;
                border-radius: 2px;
                display: block;
                cursor: pointer;
            }
        }
        .info {
            display: table-cell;
            vertical-align: middle;
            word-wrap: break-word;
            word-break: break-all;
            width: 2000px;
            .nickname {
                .name {
                    display: inline-block;
                    font-weight: 400;
                    width: 156px;
                    overflow: hidden;
                    text-overflow: ellipsis;
                    white-space: nowrap;
                    word-wrap: normal;
                    color: #fff;
                    font-size: 18px;
                    vertical-align: top;
                    line-height: 31px;
                    text-decoration: none;
                }
                .opt {
                    display: inline-block;
                    vertical-align: top;
                    cursor: pointer;
                    .menu {
                        display: inline-block;
                        vertical-align: middle;
                        width: 30px;
                        height: 30px;
                        background: url("../../assets/icon_more.png")
                    }
                }
            }
        }
    }
    .tab {
        overflow: hidden;
        position: relative;
        padding: 5px 0 10px;
        .tab-item {
            float: left;
            width: 33.33333333%;
            position: relative;
            a {
                display: block;
                text-align: center;
            }
            &:after {
                content: "";
                position: absolute;
                top: 7px;
                right: 0;
                width: 0;
                height: 20px;
                border-right: 1px solid #1D2229;
            }
        }
        &:after {
            content: "";
            position: absolute;
            border-bottom: 1px solid #1D2229;
            height: 0;
            bottom: 0;
            left: 0;
            right: 0;
        }
    }
    .group-tab {
        position: relative;
        display: flex;
        height: 40px;
        align-items: center;
        background-color: #232A39;
        .tab-item {
            flex: 1;
            text-align: center;
            a {
                position: relative;
                color: #fff;
                font-size: 14px;
                cursor: pointer;
            }
            &:first-child {
                border-right: 1px solid #1D2229;
            }
            &.active {
                a:after {
                    display: block;
                    position: absolute;
                    left: 0;
                    bottom: -11px;
                    content: '';
                    width: 100%;
                    height: 2px;
                    background-color: #4288FF;
                }
            }
        }
    }
    .nav-view {
        position: absolute;
        top: 160px;
        right: 0;
        bottom: 0;
        left: 0;
        overflow: hidden;
        .nav-message {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 36px;
            line-height: 36px;
            background-color: #ffdfe0;
            animation-duration: 1s;
            animation-fill-mode: both;
            transform: translate3d(0, -100%, 0);
            padding: 0 20px;
            z-index: 999999;
            cursor: pointer;
            .text {
                padding-left: 5px;
                color: #5e4646;
                font-size: 14px;
            }
            .connect {
                vertical-align: -3px;
                margin-right: 5px;
            }
            .button {
                position: absolute;
                right: 52px;
                top: 8px;
                line-height: 20px;
                border-radius: 20px;
                padding: 0 10px;
                font-size: 12px;
                color: #fff;
                background-color: #f66260;
            }
            &.active {
                animation-name: fadeInDown;
            }
            @keyframes fadeInDown {
                0% {
                    opacity: 0;
                    transform: translate3d(0, -36px, 0);
                }

                100% {
                    position: relative;
                    opacity: 1;
                    transform: none;
                }
            }
        }
        .nav-loading {
            text-align: center;
            margin: 30px auto;
            font-size: 14px;
            color: #6b6f7c;
            img {
                vertical-align: -3px;
                margin-right: 5px;
            }
        }
    }
    .chat-list {
        .chat-item {
            overflow: hidden;
            padding: 12px 18px 11px;
            border-bottom: 1px solid #292c33;
            cursor: pointer;
            position: relative;
            &:hover {
                background-color: #464e5d;
            }
            &.active {
                background-color: #586275;
                .ext {
                    color: #9DA4B3;
                }
            }
            .ext {
                float: right;
                color: #6b6f7c;
                font-size: 13px;
                text-align: right;
                .attr {
                    height: 19px;
                    line-height: 1.5;
                }
            }
            .avatar {
                float: left;
                margin-right: 10px;
                position: relative;
                .img {
                    display: block;
                    width: 40px;
                    height: 40px;
                    border-radius: 2px;
                }
            }
            .info {
                overflow: hidden;
                .nickname {
                    font-weight: 400;
                    font-size: 13px;
                    color: #fff;
                    line-height: 20px;
                    .text {
                        display: inline-block;
                        vertical-align: top;
                        width: 100%;
                        overflow: hidden;
                        text-overflow: ellipsis;
                        white-space: nowrap;
                        word-wrap: normal;
                    }
                }
                .msg {
                    color: #989898;
                    font-size: 13px;
                    width: 100%;
                    overflow: hidden;
                    text-overflow: ellipsis;
                    white-space: nowrap;
                    word-wrap: normal;
                    height: 1.5em;
                }
            }
            .num {
                position: absolute;
                right: 18px;
                bottom: 13px;
                height: 16px;
                line-height: 16px;
                border-radius: 16px;
                font-size: 12px;
                color: #fff;
                padding: 0 5px;
                background-color: #e62e2e;
            }
            .mute {
                position: absolute;
                right: 20px;
                bottom: 13px;
                height: 16px;
                line-height: 16px;
                border-radius: 16px;
                font-size: 12px;
                color: #fff;
                padding: 0 5px;
            }
            .mute-num {
                position: absolute;
                right: 12px;
                bottom: 19px;
                height: 16px;
                width: 6px;
                height: 6px;
                border-radius: 100%;
                background-color: #D0021B;
            }
        }
    }
    .person-list {
        .person-title {
            padding: 1px 18px;
            font-weight: 400;
            color: #787b87;
            background: #292d32;
            font-size: 14px;
        }
        .person-item {
            overflow: hidden;
            padding: 10px 18px 9px;
            border-bottom: 1px solid #292c33;
            cursor: pointer;
            &:hover {
                background-color: #464e5d;
            }
            &.active {
                background-color: #586275;
            }
            .avatar {
                float: left;
                margin-right: 10px;
                .img {
                    display: block;
                    width: 30px;
                    height: 30px;
                    border-radius: 2px;
                }
            }
            .info {
                overflow: hidden;
                line-height: 30px;
                .nickname {
                    color: #fff;
                    font-weight: 400;
                    font-size: 13px;
                    width: 100%;
                    overflow: hidden;
                    text-overflow: ellipsis;
                    white-space: nowrap;
                    word-wrap: normal;
                }
            }
        }
    }
}
</style>
